use std::env;
use std::fs;
use std::path::Path;
use agent::generic::ProviderConfig;
use autosite::to_markdown::MarkdownResult;
use autosite::trans_site::{make_trans_site_callbox, TranslationConfig};
use common::compose::make_empty_ctx;
use dotenvy::dotenv;
use trans::trans_provider::TargetLang;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 初始化环境变量和日志
    dotenv().ok();
    env_logger::init();

    // 获取 API 密钥
    let api_key = env::var("OPENAI_API_KEY").expect("OPENAI_API_KEY 环境变量未设置");
    let base_url = env::var("OPENAI_BASE_URL").ok();

    // 创建一些测试 Markdown 结果
    let markdown_dir = Path::new("output/md/en");
    if !markdown_dir.exists() {
        println!("创建测试 Markdown 目录");
        fs::create_dir_all(markdown_dir)?;
        
        // 创建一个测试 Markdown 文件
        let test_content = r#"# Test Markdown File

This is a test Markdown file for translation.

## Features

- Simple formatting
- Code blocks
- Lists

## Code Example

```rust
fn main() {
    println!("Hello, world!");
}
```

## Conclusion

This is just a test file to demonstrate the translation functionality.
"#;
        
        fs::write(markdown_dir.join("test.md"), test_content)?;
    }
    
    // 读取 Markdown 文件
    let mut markdown_results = Vec::new();
    for entry in fs::read_dir(markdown_dir)? {
        let entry = entry?;
        let path = entry.path();
        if path.is_file() && path.extension().map_or(false, |ext| ext == "md") {
            let content = fs::read_to_string(&path)?;
            let url = format!("https://example.com/{}", path.file_name().unwrap().to_string_lossy());
            
            markdown_results.push(MarkdownResult {
                url,
                content,
                lang: "en".to_string(),
                output_path: Some(path),
            });
        }
    }
    
    if markdown_results.is_empty() {
        println!("没有找到 Markdown 文件，请先运行 markdown_example.rs");
        return Ok(());
    }
    
    // 创建翻译配置
    let translation_config = TranslationConfig {
        output_dir: "output/md".to_string(),
        translator_provider_config: ProviderConfig::OpenAI {
            api_key,
            base_url,
            temperature: 0.3,
            max_tokens: None,
        },
        translator_model: "gpt-4o-mini".to_string(),
        target_lang: TargetLang::Zh,
        parallel_num: 2,
    };

    // 创建翻译器
    println!("开始翻译 Markdown 文件...");
    let translation_callbox = make_trans_site_callbox(translation_config);

    // 执行翻译
    let translation_results = translation_callbox.run(markdown_results, make_empty_ctx()).await?;
    println!("翻译完成，共翻译 {} 个文件", translation_results.len());

    // 输出结果
    for result in &translation_results {
        println!("URL: {}", result.url);
        println!("源语言: {}", result.source_lang);
        println!("目标语言: {}", result.target_lang);
        if let Some(path) = &result.output_path {
            println!("输出文件: {}", path.display());
        }
        println!("内容长度: {} 字节", result.content.len());
        println!("---");
    }

    Ok(())
}
